/**
 * @BelongsProject: zzyl-cp423
 * @BelongsPackage: com.zzyl.framework.interceptor
 * @Author: 王明天
 * @CreateTime: 2025/1/10 10:01
 * @Description: MemberInterceptor
 */
package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 小程序拦截器
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是Controller层的请求，直接放行,可以判断是否是Controller层的请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

       //判断请求是否携带token
        String token = request.getHeader("authorization");

        //没有携带直接设置401状态码，返回false
        if (StringUtils.isEmpty(token)) {

            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;

        }

        //携带token,解析token
        //判断token是否解析成功，不成功设置401状态码，返回false
        Claims claims;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }


        // 成功解析，获取其中的userId
        Long userId ;
        try {
            userId = MapUtil.get(claims, "userId", Long.class);
        } catch (NumberFormatException e) {
            // 如果userId不是一个有效的数字，则设置401状态码并返回false
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //判断userId是否为空
        if(ObjectUtil.isEmpty(userId)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //将userId放入到ThreadLocal中
        UserThreadLocal.set(userId);

        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       UserThreadLocal.remove();
    }
}
